<!DOCTYPE html>
<html lang="en">
<head>
	<meta charset="UTF-8">
	<title>AJAX 上传图片</title>
</head>
<body>
	<img id="show-img" src="" alt="" style="width: 100px;height: 50px;">
	<form action="">
		<input id="img" type="file" name="img">
		<input id="btn" type="button" value="ajax上传">
	</form>
	<script type="text/javascript" src="../../js/jquery-3.3.1.js"></script>
	<script type="text/javascript" src="../../js/layer/layer.js"></script>
	<script>
		$('#btn').click(function(){
			var file = $("#img").val();
			if(!file){
				layer.msg('选择上传文件');
				return;
			}
			// console.log($("input[name='img']")[0].files[0]);
			var formdata = new FormData();
			var file = $("input[name='img']")[0].files[0];
			formdata.append('img',file);
			$.ajax({
		            url: "../php/upload.php",
		            type: "POST",
		            data: formdata,
		            contentType: false,
		            processData: false,
		            success: function (data) {
		               	console.log(data);
		               	$('#show-img').attr('src',data);
		            },
		            error: function () {
		                alert('上传失败');
		            }
		        });
		});
	</script>
</body>
</html> 